﻿#nullable enable

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using System.ComponentModel.DataAnnotations;
using System.Reflection;

namespace Admin.NET.Core
{
    public static class FieldUtil
    {
        /// <summary>
        /// 获取标量属性是否必须
        /// </summary>
        /// <param name="p"></param>
        /// <param name="dataType"></param>
        /// <returns></returns>
        public static bool IsRequired(IProperty p, string dataType)
        {
            if (dataType.StartsWith("System.Nullable"))
            {
                return false;
            }

            if ("System.String".Equals(dataType))
            {
                return p.PropertyInfo?.IsDefined(typeof(RequiredAttribute), true) ?? false;
            }
            
            return true;
        }

        /// <summary>
        /// 获取导航属性是否必须
        /// </summary>
        /// <param name="p"></param>
        /// <param name="dataType"></param>
        /// <returns></returns>
        public static bool IsRequired(INavigation p, string dataType)
        {
            if (dataType.StartsWith("System.Nullable"))
            {
                return false;
            }          
            return true;
        }

        /// <summary>
        /// 获取导航属性是否注解信息
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public static string GetComment(this INavigation p)
        {
            return ((CommentAttribute?)p?.PropertyInfo?.GetCustomAttribute(typeof(CommentAttribute), true))?.Comment ?? "";
        }


        /// <summary>
        /// 获取类型检称
        /// </summary>
        /// <param name="fullName"></param>
        /// <returns></returns>
        public static string GetSimpleName(this string fullName) 
        {
            var args = fullName.Split(".");
            if (args == null) return "";
            return args[^1];
        }

       
       
    }
}
